<template>
  <div class="app-container">
    <!-- 添加状态选项卡 -->
    <el-tabs v-model="activeStatus" @tab-change="handleStatusChange">
      <el-tab-pane label="已上架商品" name="1"></el-tab-pane>
      <el-tab-pane label="已下架商品" name="2"></el-tab-pane>
    </el-tabs>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="商品编码" prop="productCode">-->
<!--        <el-input-->
<!--          v-model="queryParams.productCode"-->
<!--          placeholder="请输入商品编码"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="productCategoryName">
        <el-select
            v-model="queryParams.productCategoryName"
            clearable
            style=" width: 200px">
          <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="首页展示" prop="productShow">
        <el-select
            v-model="queryParams.productShow"
            clearable
            style="width: 200px">
          <el-option v-for="dict in sys_yes_no2"
                     :key="dict.value"
                     :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="为你推荐" prop="productRecommended">
        <el-select
            v-model="queryParams.productRecommended"
            clearable
            style="width: 200px">
          <el-option
              v-for="dict in sys_yes_no2"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="新品上新" prop="productNew">
        <el-select
            v-model="queryParams.productNew"
            clearable
            style="width: 200px">
          <el-option
              v-for="dict in sys_yes_no2"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"/>
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="价格" prop="productPrice">-->
<!--        <el-input-->
<!--          v-model="queryParams.productPrice"-->
<!--          placeholder="请输入价格"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="销量" prop="productSalesVolume">-->
<!--        <el-input-->
<!--          v-model="queryParams.productSalesVolume"-->
<!--          placeholder="请输入销量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="库存" prop="productStock">-->
<!--        <el-input-->
<!--          v-model="queryParams.productStock"-->
<!--          placeholder="请输入库存"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="计量单位" prop="productUnit">-->
<!--        <el-input-->
<!--          v-model="queryParams.productUnit"-->
<!--          placeholder="请输入计量单位"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="商品简介" prop="productSummary">-->
<!--        <el-input-->
<!--          v-model="queryParams.productSummary"-->
<!--          placeholder="请输入商品简介"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="发货地" prop="productOrigin">-->
<!--        <el-input-->
<!--          v-model="queryParams.productOrigin"-->
<!--          placeholder="请输入发货地"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="运费" prop="productFee">-->
<!--        <el-input-->
<!--          v-model="queryParams.productFee"-->
<!--          placeholder="请输入运费"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="商品详情" prop="productDetails">-->
<!--        <el-input-->
<!--          v-model="queryParams.productDetails"-->
<!--          placeholder="请输入商品详情"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="虚拟销量" prop="productSales">-->
<!--        <el-input-->
<!--          v-model="queryParams.productSales"-->
<!--          placeholder="请输入虚拟销量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:product1:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:product1:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleDelete"
          v-hasPermi="['system:product1:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:product1:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="product1List" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:product1:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:product1:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="商品编码" align="center" prop="productCode" />
      <el-table-column label="商品封面图" align="center" prop="productImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.productImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品分类名称" align="center" prop="productCategoryName" />
      <el-table-column label="价格" align="center" prop="productPrice" />
      <el-table-column label="销量" align="center" prop="productSalesVolume" />
      <el-table-column label="库存" align="center" prop="productStock" />
      <el-table-column label="状态" align="center" prop="productStatus" >
        <template #default="scope">
          <el-tag  :type="scope.row.productStatus === 1 ? 'success' : 'danger' ">
            {{ scope.row.productStatus === 1 ? '已上架' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="计量单位" align="center" prop="productUnit" />-->
<!--      <el-table-column label="商品简介" align="center" prop="productSummary" />-->
<!--      <el-table-column label="商品轮播图" align="center" prop="productImage2" width="100">-->
<!--        <template #default="scope">-->
<!--          <image-preview :src="scope.row.productImage2" :width="50" :height="50"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="发货地" align="center" prop="productOrigin" />-->
<!--      <el-table-column label="运费" align="center" prop="productFee" />-->
<!--      <el-table-column label="商品详情" align="center" prop="productDetails" />-->
<!--      <el-table-column label="虚拟销量" align="center" prop="productSales" />-->
<!--      <el-table-column label="排序" align="center" prop="productCategoryId" />-->

    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="90%" append-to-body>
      <el-form ref="product1Ref" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="productCategoryName">
          <el-select
              v-model="form.productCategoryName"
              clearable
              style=" width: 200px">
            <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计量单位" prop="productUnit" required>
          <el-select v-model="form.productUnit" placeholder="请输入计量单位" >
            <el-option
                v-for="item in unit"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品简介" prop="productSummary">
          <el-input v-model="form.productSummary" placeholder="请输入商品简介" type="textarea"  :autosize="{minRows: 4, maxRows: 4}"/>
        </el-form-item>
<!--        <el-form-item label="商品编码" prop="productCode">-->
<!--          <el-input v-model="form.productCode" placeholder="请输入商品编码" />-->
<!--        </el-form-item>-->
        <el-form-item label="商品封面图" prop="productImage">
          <image-upload v-model="form.productImage"/>
        </el-form-item>
        <el-form-item label="商品轮播图" prop="productImage2">
          <image-upload v-model="form.productImage2"/>
        </el-form-item>
        <el-form-item label="商品规格" prop="productSku">
          <el-radio-group v-model="form.specType" @change="handleSpecTypeChange">
            <el-radio :label="1">单规格</el-radio>
            <el-radio :label="2" >多规格</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 单规格表格 -->
        <el-table
            v-if="form.specType === 1"
            :data="singleSpecData"
            border
            style="width: 100%; margin-bottom: 20px">
          <el-table-column label="图片" width="120">
            <template #default="scope">
              <image-upload v-model="scope.row.image" :show-file-list="false" />
            </template>
          </el-table-column>
          <el-table-column label="售价" prop="price">
            <template #default="scope">
              <el-input v-model="scope.row.price" placeholder="请输入售价" />
            </template>
          </el-table-column>
          <el-table-column label="成本价" prop="costPrice">
            <template #default="scope">
              <el-input v-model="scope.row.costPrice" placeholder="请输入成本价" />
            </template>
          </el-table-column>
          <el-table-column label="原价" prop="originalPrice">
            <template #default="scope">
              <el-input v-model="scope.row.originalPrice" placeholder="请输入原价" />
            </template>
          </el-table-column>
          <el-table-column label="库存" prop="stock">
            <template #default="scope">
              <el-input v-model="scope.row.stock" placeholder="请输入库存" />
            </template>
          </el-table-column>
          <el-table-column label="商品编号" prop="sku">
            <template #default="scope">
              <el-input v-model="scope.row.sku" placeholder="请输入商品编号" />
            </template>
          </el-table-column>
          <el-table-column label="重量(KG)" prop="weight">
            <template #default="scope">
              <el-input v-model="scope.row.weight" placeholder="请输入重量" />
            </template>
          </el-table-column>
          <el-table-column label="体积(m³)" prop="volume">
            <template #default="scope">
              <el-input v-model="scope.row.volume" placeholder="请输入体积" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="form.specType === 2">
          <el-button type="primary" size="small" @click="addSpecGroup" style="margin-bottom: 10px;">
                    添加规格组
          </el-button>
          <el-table
              v-for="(group, groupIndex) in multiSpecGroups"
              :key="groupIndex"
              :data="group.specs"
              border
              style="width: 100%; margin-bottom: 20px">
            <el-table-column :label="'规格组 ' + (groupIndex + 1)" >
              <template #header>
                <el-input v-model="group.name" placeholder="规格组名称"  />
                <el-button type="danger" size="small" @click="removeSpecGroup(groupIndex)" style="margin-left: 10px;">
                  删除
                </el-button>
              </template><template #default="scope">
              <el-input v-model="scope.row.value" placeholder="规格值（颜色、尺寸）" />
            </template>
            </el-table-column>
            <el-table-column label="图片" >
              <template #default="scope">
                <image-upload v-model="scope.row.image" :show-file-list="false" />
              </template>
            </el-table-column>
            <el-table-column label="售价" prop="price">
              <template #default="scope">
                <el-input v-model="scope.row.price" placeholder="请输入售价" />
              </template>
            </el-table-column>
            <el-table-column label="成本价" prop="costPrice">
              <template #default="scope">
                <el-input v-model="scope.row.costPrice" placeholder="请输入成本价" />
              </template>
            </el-table-column>
            <el-table-column label="原价" prop="originalPrice">
              <template #default="scope">
                <el-input v-model="scope.row.originalPrice" placeholder="请输入原价" />
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="stock">
              <template #default="scope">
                <el-input v-model="scope.row.stock" placeholder="请输入库存" />
              </template>
            </el-table-column>
            <el-table-column label="商品编号" prop="sku">
              <template #default="scope">
                <el-input v-model="scope.row.sku" placeholder="请输入商品编号" />
              </template>
            </el-table-column>
            <el-table-column label="重量(KG)" prop="weight">
              <template #default="scope">
                <el-input v-model="scope.row.weight" placeholder="请输入重量" />
              </template>
            </el-table-column>
            <el-table-column label="体积(m³)" prop="volume">
              <template #default="scope">
                <el-input v-model="scope.row.volume" placeholder="请输入体积" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button type="danger" size="small" @click="removeSpec(groupIndex, scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>


        <el-form-item label="发货地" prop="productOrigin">
          <el-col :span="12">
            <el-select v-model="form.province" @change="handleProvinceChange"  placeholder="选择省份">
              <el-option v-for="item in regionData.provinces" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-select v-model="form.city" :disabled="!form.province"  placeholder="选择城市">
              <el-option v-for="item in regionData.cities" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-col>
        </el-form-item>

        <el-form-item label="运费" prop="productFee">
          <el-input v-model="form.productFee" placeholder="请输入运费" />
        </el-form-item>
        <el-form-item label="商品详情" prop="productDetails">
          <el-input v-model="form.productDetails" placeholder="请输入商品详情" />
        </el-form-item>
        <el-form-item label="虚拟销量" prop="productSales">
          <el-radio-group v-model="form.productSales">
            <el-radio  v-for="dict in sys_yes_no"
                       :key="dict.value"
                       :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
            <el-input  placeholder="请填写虚拟销量" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="productCategoryId">
          <el-input
              v-model="form.sortOrder"
              :min="0"
              controls-position="right"
              placeholder="不填则系统自动生成"
          />
        </el-form-item>
        <el-form-item label="状态" prop="productStatus">
          <el-radio-group v-model="form.productStatus">
            <el-radio
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="首页展示" prop="productShow">
          <el-radio-group v-model="form.productShow" placeholder="请输入首页展示" >
            <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="为你推荐" prop="productRecommended">
          <el-radio-group v-model="form.productRecommended" placeholder="请输入为你推荐" >
            <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="新品上新" prop="productNew">
          <el-radio-group v-model="form.productNew" placeholder="请输入新品上新" >
            <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

<!--        <el-form-item label="价格" prop="productPrice">-->
<!--          <el-input v-model="form.productPrice" placeholder="请输入价格" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="销量" prop="productSalesVolume">-->
<!--          <el-input v-model="form.productSalesVolume" placeholder="请输入销量" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="库存" prop="productStock">-->
<!--          <el-input v-model="form.productStock" placeholder="请输入库存" />-->
<!--        </el-form-item>-->

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product1">
import { listProduct1, getProduct1, delProduct1, addProduct1, updateProduct1 } from "@/api/system/product1"
import {reactive,ref } from "vue";

const activeStatus = ref('1') // 默认选中已上架商品
const handleStatusChange = (status) => {
  activeStatus.value = status
  queryParams.value.productStatus = status
  handleQuery()
}

const { proxy } = getCurrentInstance()

const categoryOptions = ref([
  { value: '电子产品', label: '电子产品' },
  { value: '服装服饰', label: '服装服饰' },
  { value: '食品饮料', label: '食品饮料' },
  { value: '家居用品', label: '家居用品' },
  { value: '图书文娱', label: '图书文娱' }
])

const unit = ref([
  {value:'克',label:'G'},
  {value:'千克',label:'KG'},
  {value:'吨',label:'T'}
])
const sys_normal_disable = ref([
  { label: '已上架', value: '1' },
  { label: '已下架', value: '2' },
  { label: '未知状态',value: '0'}
])
const regionData = reactive({
  provinces: [
    { code: '11', name: '北京市' },
    { code: '12', name: '天津市' },
    { code: '13', name: '河北省' },
  ],
  cities: [] // 动态加载的城市数据
});
// 根据省份编码加载对应的城市数据
const cityData = {
  '11': [{code: '1101', name: '北京市'}],
  '12': [{code: '1201', name: '天津市'}],
  '13': [
    {code: '1301', name: '石家庄市'},
    {code: '1302', name: '唐山市'},
  ],
}
const handleProvinceChange = (provinceCode) => {
  form.value.city = ''; // 清空已选城市
  regionData.cities = cityData[provinceCode] || []; // 加载对应城市
  console.log('当前城市列表:', regionData.cities); // 调试用
};
const sys_yes_no = ref([
  { label: '开启', value: '1' },
  { label: '关闭', value: '0' }
])
const sys_yes_no2 = ref([
  { label: '是', value: '1' },
  { label: '否', value: '0' }
])
// 规格相关数据
const singleSpecData = ref([{
  image: '',
  price: '',
  costPrice: '',
  originalPrice: '',
  stock: '',
  sku: '',
  weight: '0',
  volume: '0'
}])
// 多规格
const multiSpecGroups = ref([
  {
    name: '颜色',
    specs: [
      { value: '红色', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' },
      { value: '蓝色', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' }
    ]
  },
  {
    name: '尺寸',
    specs: [
      { value: 'S', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' },
      { value: 'M', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' }
    ]
  }
]);
const product1List = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productCode: null,
    productImage: null,
    productName: null,
    productCategoryName: null,
    productPrice: null,
    productSalesVolume: null,
    productStock: null,
    productStatus: 1,
    productUnit: null,
    productSummary: null,
    productImage2: null,
    productOrigin: null,
    productFee: null,
    productDetails: null,
    productSales: null,
    productShow: null,
    productRecommended: null,
    productNew: null,
    productSku: null
  },
  rules: {
    productCode: [
      { required: true, message: "商品编码不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    productPrice: [
      { required: true, message: "价格不能为空", trigger: "blur" }
    ],
    // productStock: [
    //   { required: true, message: "库存不能为空", trigger: "blur" }
    // ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 添加规格组
const addSpecGroup = () => {
  multiSpecGroups.value.push({
    name: '新规格组',
    specs: [{ value: '', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' }]
  });
};

// 删除规格组
const removeSpecGroup = (index) => {
  multiSpecGroups.value.splice(index, 1);
};

// 添加规格项
const addSpecItem = (groupIndex) => {
  multiSpecGroups.value[groupIndex].specs.push({
    value: '',
    image: '',
    price: '',
    costPrice: '',
    originalPrice: '',
    stock: '',
    sku: '',
    weight: '0',
    volume: '0'
  });
};

// 删除规格项
const removeSpec = (groupIndex, specIndex) => {
  multiSpecGroups.value[groupIndex].specs.splice(specIndex, 1);
};


/** 查询商品信息管理列表 */
function getList() {
  loading.value = true
  listProduct1(queryParams.value).then(response => {
    product1List.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    productCode: null,
    productImage: null,
    productName: null,
    productCategoryName: null,
    productPrice: null,
    productSalesVolume: null,
    productStock: null,
    productStatus: null,
    productUnit: null,
    productSummary: null,
    productImage2: null,
    productOrigin: null,
    productFee: null,
    productDetails: null,
    productSales: null,
    productCategoryId: null,
    productShow: null,
    productRecommended: null,
    productNew: null,
    productSku: null,
    specType:1,
    province: '',
    city: ''
  }
  // 重置单规格数据
  singleSpecData.value = [{
    image: '',
    price: '',
    costPrice: '',
    originalPrice: '',
    stock: '',
    sku: '',
    weight: '0',
    volume: '0'
  }]

  // 重置多规格数据
  multiSpecGroups.value = [
    {
      name: '颜色',
      specs: [
        { value: '红色', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' },
        { value: '蓝色', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' }
      ]
    },
    {
      name: '尺寸',
      specs: [
        { value: 'S', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' },
        { value: 'M', image: '', price: '', costPrice: '', originalPrice: '', stock: '', sku: '', weight: '0', volume: '0' }
      ]
    }
  ]

  proxy.resetForm("product1Ref")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.productCategoryId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新增商品"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _productCategoryId = row.productCategoryId || ids.value
  getProduct1(_productCategoryId).then(response => {
    form.value = response.data
    // 回填规格数据
    if (form.value.specType === 1 && form.value.skuList && form.value.skuList.length > 0) {
      singleSpecData.value = form.value.skuList
    } else if (form.value.specType === 2 && form.value.skuList) {
      multiSpecGroups.value = parseMultiSpecData(form.value.skuList)
    }
    open.value = true
    title.value = "修改商品"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["product1Ref"].validate(valid => {
    if (valid) {
      // 拼接发货地（如：北京市-北京市）
      const provinceName = regionData.provinces.find(p => p.code === form.value.province)?.name || '';
      const cityName = regionData.cities.find(c => c.code === form.value.city)?.name || '';
      form.value.productOrigin = `${provinceName}-${cityName}`;
    }

      if (valid) {
      // 处理规格数据
      if (form.value.specType === 1) {
        form.value.skuList = singleSpecData.value
        // 同步单规格数据到主表单
        if (singleSpecData.value.length > 0) {
          form.value.productPrice = singleSpecData.value[0].price
          form.value.productCode = singleSpecData.value[0].sku
          form.value.productStock = singleSpecData.value[0].stock
        }
      }else {
        form.value.skuList = generateMultiSpecCombinations()
        // 同步多规格数据到主表单（取第一个规格的值）
        if (multiSpecGroups.value.length > 0 &&
            multiSpecGroups.value[0].specs.length > 0) {
          form.value.productPrice = multiSpecGroups.value[0].specs[0].price
          form.value.productCode = multiSpecGroups.value[0].specs[0].sku
          form.value.productStock = singleSpecData.value[0].stock
        }
      }
      if (form.value.productCategoryId != null) {
        updateProduct1(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProduct1(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
//规格 表
const generateMultiSpecCombinations = () => {
  // 简单实现 - 实际应根据规格组生成笛卡尔积
  const combinations = [];
  multiSpecGroups.value.forEach(group => {
    group.specs.forEach(spec => {
      combinations.push({
        specs: `${group.name}:${spec.value}`,
        price: spec.price,
        costPrice: spec.costPrice,
        originalPrice: spec.originalPrice,
        stock: spec.stock,
        sku: spec.sku,
        weight: spec.weight,
        volume: spec.volume,
        image: spec.image
      });
    });
  });
  return combinations;
};
/** 删除按钮操作 */
function handleDelete(row) {
  const _productCategoryIds = row.productCategoryId || ids.value
  proxy.$modal.confirm('是否确认删除商品信息管理编号为"' + _productCategoryIds + '"的数据项？').then(function() {
    return delProduct1(_productCategoryIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/product1/export', {
    ...queryParams.value
  }, `product1_${new Date().getTime()}.xlsx`)
}

getList()
</script>
